﻿using System.Collections.Generic;
using UnityEngine;
using System.Linq;

namespace ZyGame.Drawing
{
    public class DrawingRecord
    {
        class CacheData
        {
            public Texture2D next;
            public Texture2D prev;
            public RenderTexture target;
        }

        /// <summary>
        /// 当前缓存
        /// </summary>
        private static CacheData cache;

        private static int current = 0;
        private static List<CacheData> caches = new List<CacheData>();

        public static void Start(RenderTexture texture)
        {
            if (cache != null)
            {
                return;
            }
            if (current < caches.Count - 1)
            {
                for (int i = caches.Count - 1; i > current; i--)
                {
                    caches.Remove(caches[i]);
                }
            }
            cache = new CacheData();
            cache.target = texture;
            cache.prev = texture.ReadTexture2D();
        }

        public static void Ended(RenderTexture texture)
        {
            if (cache == null)
            {
                return;
            }
            cache.next = texture.ReadTexture2D();
            caches.Add(cache);
            if (caches.Count > 10)
            {
                caches.Remove(caches.First());
            }
            cache = null;
            current = caches.Count - 1;
        }

        public static void Forwad()
        {
            if (current >= caches.Count - 1)
            {
                return;
            }
            current++;
            CacheData cache = caches[current];
            cache.target.Clear();
            cache.target.DrawTexture(new Rect(0, 0, cache.next.width, cache.next.height), cache.next, null);
        }

        public static void Backup()
        {
            if (current <= 0)
            {
                return;
            }
            current--;
            CacheData cache = caches[current];
            cache.target.Clear();
            cache.target.DrawTexture(new Rect(0, 0, cache.prev.width, cache.prev.height), cache.prev, null);
        }
    }
}